package org.jeecgframework.web.service.impl;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.HashMap;

import org.apache.commons.mail.Email;
import org.apache.commons.mail.SimpleEmail;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.jeecgframework.web.service.ZyEmailService;
import org.jeecgframework.web.system.pojo.base.ZyEmailEntity;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.SendMailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("zyEmailService")
public class ZyEmailServiceImpl implements ZyEmailService {

	@Autowired
	private SystemService systemService;
	
	public void sendEmail(ZyEmailEntity emailEntity) throws Exception {
		// obtain message model data 
		Map<String, Object> root = new HashMap<String, Object>();
		root.put("name", "chen jing");

		// generate attachment 
		this.generateAttachment(emailEntity);

		// resolve email template 
		// temporary 
		String emailTemplate = this.resolveEmailTemplate(emailEntity);
		
		// send the email
//		SendMailUtil.sendFtlMail(emailEntity, emailTemplate, root,systemService);
    }
	
	/**
	 * resolve email's content template according to {emailEntity}
	 * @param emailEntity
	 * @return
	 */
	private String resolveEmailTemplate(ZyEmailEntity emailEntity) {
		return "emailTemplate.ftl";
	}

	/**
	 * generate attachment according to email type
	 */
	private void generateAttachment(ZyEmailEntity emailEntity) throws Exception {
		String emailType = emailEntity.getEmailType();

		// do nothing if email type is default {null}
		if(null == emailType) {
			return;
		} 

		// generate attachment
		// to do...
		int byteArrayCapacity = 20000;
		ByteArrayOutputStream os = null;
		String attachmentName = null;
		String attachmentDesc = null;
		if ("1".equals(emailType)) {
			// create word document 
			XWPFDocument document = new XWPFDocument();
			XWPFParagraph paragraph = document.createParagraph();
			XWPFRun run = paragraph.createRun();
			run.setText("this is test document");
			
			// write document to byte array
			os = new ByteArrayOutputStream(byteArrayCapacity);
			try {
	            document.write(os);
            } catch (IOException e) {
	            e.printStackTrace();
	            throw new Exception("附件文档生成失败！");
            }
			
			// assign values to attachment's name and description
			attachmentName = "test.docx";
			attachmentDesc = "this is one test word file.";
		}
		
		// attach document to email
		emailEntity.setEmailAttachment(os.toByteArray());
		emailEntity.setEmailAttachmentName(attachmentName);
		emailEntity.setEmailAttachmentDesc(attachmentDesc);
	}
}
